/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#include <thrift/thrift-config.h>

#include <thrift/concurrency/ThreadFactory.h>
#include <thrift/concurrency/Exception.h>
#include <thrift/concurrency/IOService.h>

#include <cassert>

#include <boost/weak_ptr.hpp>
#include <boost/thread.hpp>

namespace apache {
namespace thrift {
namespace concurrency {

using boost::shared_ptr;
using boost::weak_ptr;

boost::once_flag IOService::flags_ = BOOST_ONCE_INIT;
boost::shared_ptr<Thread> IOService::thr_;
boost::shared_ptr<IOService> IOService::instance_;


IOService::IOService(int32_t hints)
  :io_service_(hints)
{

}

IOService::~IOService()
{
  stop();
}

void IOService::run()
{
  for (;;){
    boost::asio::io_service::work loopwork(io_service_);
    try {
      io_service_.run();
      break;
    }
    catch (std::exception& e) {
      TLogging::log_err("error %s", e.what());
    }
    catch (...) {
      TLogging::log_err("IOService:run(): unknown error\n");
    }
  }
}

void IOService::stop()
{
  io_service_.stop();
  thr_->join();
}

boost::asio::io_service& IOService::getDefaultIOService(int32_t hints)
{
  boost::call_once(boost::bind(createInstance, hints), flags_);
  return instance_->getIOService();
}

void IOService::createInstance(int32_t hints)
{
  instance_ = boost::make_shared<IOService>();
  boost::shared_ptr<ThreadFactory> thrfactory(new ThreadFactory);
  thr_ = thrfactory->newThread(instance_);
  thr_->start();
}

}
}
} // apache::thrift::concurrency
